<?php

namespace app\common\library\agent\comission;


use app\common\model\OrderGoods;
use app\common\model\User;
use think\Log;

abstract class CommissionPlugin implements Commission
{
    protected $configs;
    protected $order;
    protected $ratio;
    /**
     */
    protected $listener;
    /**
     * @var User 订单创建者
     */
    protected $orderCreator;
    protected $commissionType;


    abstract function getCommission($set, $price);

    /**
     * 分佣主逻辑
     * @param $orderGoods OrderGoods 订单明细
     */
    function doCommission($commissionType, $order, $orderGoods)
    {
        Log::record("分佣方式 --> ".$commissionType);
        $this->order = $order;
        $this->orderCreator = User::get($this->order->user_id);
        $creatorLevel = $this->orderCreator->agent_level;
        Log::record("下单者级别 --> ".$creatorLevel);
        $this->commissionType = $commissionType;
        if ($creatorLevel < 4) {
            Log::record('下单者本身是代理，相当于直接分享的客户下了个单');
            $set = $this->configs[$this->orderCreator->agent_level][4];
            $commission = $this->getCommission($set, $orderGoods->goods_price);
            Log::record("所得分润 --> ".$commission);
            $ratio = $this->getRatio($set);
            Log::record("分润比例 --> ".$ratio);
            $this->listener->afterCommission($commission, $this->order, $this->orderCreator,
                $orderGoods, $orderGoods->total_num, $this->orderCreator, $ratio);
        }
        $this->calUppers($this->orderCreator, $this->order, $this->orderCreator, $orderGoods, $orderGoods->total_num);
    }

    protected function getRatio($set)
    {
        return $this->commissionType == 'fix' ? null : $set;
    }

    protected function calUppers($user, $order, $orderCreator, $orderGoods, $total_num)
    {
        if ($user->upper_id > 0) { //存在上级代理
            Log::record("计算上级代理分润 --> ".$user->upper_id);
            $upper = User::get($user->upper_id);
            if ($upper) {
                //给上级分佣
                $set = $this->configs[$upper->agent_level][$user->agent_level];
                $commission = $this->getCommission($set, $orderGoods->goods_price);
                Log::record("上级分润 --> ".$commission);
                $this->listener->afterCommission($commission, $order, $orderCreator, $orderGoods, $total_num, $upper, $this->getRatio($set));
                $this->calUppers($upper, $order, $orderCreator, $orderGoods, $total_num);
            }
        }
    }

    function setListener(CommissionListener $listener)
    {
        $this->listener = $listener;
    }

    function config($configs)
    {
        $this->configs = $configs;
    }
}